//
//  ExRxTableViewController.swift
//  Swift-Example
//
//  Created by apang on 2018/8/8.
//  Copyright © 2018 apang.men All rights reserved.
//

import UIKit
import RxCocoa
import RxSwift
import RxDataSources

class ExRxTableViewController: UITableViewController {
    
    var dataSource: RxTableViewSectionedReloadDataSource<ProvinceModel>?
    var disposeBag = DisposeBag()
    let dataManager: RxTableViewDataManager = RxTableViewDataManager()
    override func viewDidLoad() {
        super.viewDidLoad()
        let dataSource = RxTableViewSectionedReloadDataSource<ProvinceModel>(
            configureCell: { (_, tv, indexPath, element) in
                let cell:ExRxTableViewCell = tv.dequeueReusableCell(withIdentifier: "rxCell")! as! ExRxTableViewCell
                cell.nameLabel.text = element.diji;
                return cell
            }
        )
        tableView.register(ExRxTableHeaderView().classForCoder, forHeaderFooterViewReuseIdentifier: "rxHeader")
        tableView.dataSource = nil
        tableView.delegate = nil
        
        self.dataSource = dataSource
        self.dataManager.sections?.asObservable().bind(to: tableView.rx.items(dataSource: dataSource)).disposed(by: disposeBag)
        
        tableView.rx.setDelegate(self).disposed(by: disposeBag)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        (UIApplication.shared.delegate as! AppDelegate).interfacceOrientaion = [.landscapeRight]
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let model = self.dataManager.sections?.value[section]
        if (model?.isSelect)! {
            return (model?.children.count)!
        }
        return 0
    }
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 40.0
    }
    
    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerView: ExRxTableHeaderView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "rxHeader") as! ExRxTableHeaderView
        let model = self.dataManager.sections?.value[section]
        headerView.titleLabel.text = model?.shengji
        headerView.tag = section
        headerView.rowButton.isSelected = (model?.isSelect)!
        headerView.delegate = self.dataManager
        return headerView
    }
}
